const fs = require('node:fs')
const path = require('node:path')
const http = require('http')
const { clear } = require('node:console')

requestHistory=[]
currentPort = 8080
server = {}

// 通过 window 对象向渲染进程注入 nodejs 能力
window.services = {

  // 读文件
  readFile (file) {
    return fs.readFileSync(file, { encoding: 'utf-8' })
  },
  // 文本写入到下载目录
  writeTextFile (text) {
    const filePath = path.join(window.utools.getPath('downloads'), Date.now().toString() + '.txt')
    fs.writeFileSync(filePath, text, { encoding: 'utf-8' })
    return filePath
  },
  // 图片写入到下载目录
  writeImageFile (base64Url) {
    const matchs = /^data:image\/([a-z]{1,20});base64,/i.exec(base64Url)
    if (!matchs) return
    const filePath = path.join(window.utools.getPath('downloads'), Date.now().toString() + '.' + matchs[1])
    fs.writeFileSync(filePath, base64Url.substring(matchs[0].length), { encoding: 'base64' })
    return filePath
  },
  createServer(port) {
    currentPort = port
    server = http.createServer((req, res) => {
      // 记录普通请求
      let body = []
      req.on('data', chunk => body.push(chunk))
      req.on('end', () => {
        const requestData = {
          timestamp: new Date().toLocaleString(),
          method: req.method,
          url: req.url,
          headers: req.headers,
          body: Buffer.concat(body).toString(),
          clientIP: req.socket.remoteAddress
        }
        requestHistory.push(requestData)
        
        res.writeHead(200, {
          'Content-Type': 'text/plain',
          'Access-Control-Allow-Origin': '*'
        })
        res.end('OK')
      })
    })
    server.listen(currentPort, () => {
      utools.showNotification(`HTTP监听已启动 (端口: ${currentPort})`)
    }).on('error', (err) => {
      utools.showNotification(`端口 ${currentPort} 被占用！`)
    })
  },
  closeServer() {
    server.close()
    utools.showNotification(`HTTP监听已关闭`)
  },
  getServerPort() {
    return currentPort
  },
  getServerHistory() {
    return requestHistory
  },
  getServerStatus() {
    return server.listening
  },
  clearServerHistory() {
    requestHistory = []
    return requestHistory
  },
  restartServerPort(port) {
    server?.close()
    this.createServer(port)
  }
  
}
